package zoarEE;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class register
 */
@WebServlet("/register")
public class register extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public register() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String UserName= request.getParameter("UserName");
		String Password=request.getParameter("Password");
		PrintWriter out = response.getWriter();			
		out.println("hello world");
		out.println(UserName);
		out.println(Password);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String UserName= request.getParameter("UserName");
		String Password=request.getParameter("Password");
		PrintWriter out = response.getWriter();			
		try {
			Connection conn= DB.Connect();
	        String sql = "insert into Users values (?,?)";

	        PreparedStatement pstat = conn.prepareStatement(sql);
	        pstat.setString(1, UserName);
	        pstat.setString(2, Password);
	        
	        pstat.execute();
	        out.print("Registered successfully! UserName:"+UserName+" Password:"+Password);
	        conn.close();
	        pstat.close();
	        } catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
	        out.print("Registeration failed! UserName:"+UserName+"is in use");
			e.printStackTrace();
		}
	}
}
